package com.songlanyun.modules.shop.service.impl;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.songlanyun.common.enums.MemberConstant;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.modules.config.entity.SystemUserRoleConfigEntity;
import com.songlanyun.modules.config.service.SystemUserRoleConfigService;
import com.songlanyun.modules.shop.model.dto.ShopUserRoleConfigDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.Query;

import com.songlanyun.modules.shop.dao.ShopUserRoleConfigDao;
import com.songlanyun.modules.shop.entity.ShopUserRoleConfigEntity;
import com.songlanyun.modules.shop.service.ShopUserRoleConfigService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("yxtShopUserRoleConfigService")
public class ShopUserRoleConfigServiceImpl extends ServiceImpl<ShopUserRoleConfigDao, ShopUserRoleConfigEntity> implements ShopUserRoleConfigService {

    @Resource
    private SystemUserRoleConfigService systemUserRoleConfigService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Long shopId = MapUtil.getLong(params, "shop_id");

        IPage<ShopUserRoleConfigEntity> page = this.page(
                new Query<ShopUserRoleConfigEntity>().getPage(params),
                new LambdaQueryWrapper<ShopUserRoleConfigEntity>()
                        .eq(shopId != null, ShopUserRoleConfigEntity::getShopId, shopId)
                        .orderByDesc(ShopUserRoleConfigEntity::getCreateTime)
        );

        return new PageUtils(page);
    }

    @Override
    public List<ShopUserRoleConfigEntity> select(Long shopId) {
        List<ShopUserRoleConfigEntity> list = this.list(
                new LambdaQueryWrapper<ShopUserRoleConfigEntity>()
                        .eq(shopId != null, ShopUserRoleConfigEntity::getShopId, shopId)
                        .orderByAsc(ShopUserRoleConfigEntity::getLevel)
        );

        return list;
    }

    /**
     * 初始化商家的会员等配置
     *
     * @param shopId
     * @param isJmShop 是否是加盟商家 false平台商家拷贝所有的配置，true加盟商家拷贝除市代的记录
     */
    @Override
    public void saveShopConfig(Long shopId, boolean isJmShop) {
        //查询该商家有没有商家会员等级配置
        int count = this.count(
                new LambdaQueryWrapper<ShopUserRoleConfigEntity>()
                        .eq(ShopUserRoleConfigEntity::getShopId, shopId)
        );
        if (count > 0) {//已经保存过，无需再保存
            return;
        }

        //查询平台的会员等配置--可以升级的等级配置
        List<SystemUserRoleConfigEntity> list = systemUserRoleConfigService.list(
                new LambdaQueryWrapper<SystemUserRoleConfigEntity>()
                        .eq(isJmShop, SystemUserRoleConfigEntity::getUserGrade, true)
        );

        //保存商家的会员等配置
        list.forEach(v -> {
            ShopUserRoleConfigEntity shopUserRoleConfigEntity = new ShopUserRoleConfigEntity();
            v.setId(null);//不能克隆id
            BeanUtils.copyProperties(v, shopUserRoleConfigEntity);//将平台的等级设置拷贝到商家
            shopUserRoleConfigEntity.setShopId(shopId);//设置商家id
            shopUserRoleConfigEntity.setOuterRoleName(v.getRoleName());//输出的等级名称
            this.save(shopUserRoleConfigEntity);
        });
    }

    @Override
    public ShopUserRoleConfigEntity getByShopIdAndId(Long shopId, Integer id) {
        ShopUserRoleConfigEntity one = this.getOne(new LambdaQueryWrapper<ShopUserRoleConfigEntity>()
                .eq(ShopUserRoleConfigEntity::getShopId, shopId)
                .eq(ShopUserRoleConfigEntity::getId, id)
                .last("limit 1")
        );
        return one;
    }

    @Override
    public ShopUserRoleConfigEntity getByShopIdAndRoleCode(Long shopId, String roleCode) {

        ShopUserRoleConfigEntity one = this.getOne(new LambdaQueryWrapper<ShopUserRoleConfigEntity>()
                .eq(ShopUserRoleConfigEntity::getShopId, shopId)
                .eq(ShopUserRoleConfigEntity::getRoleCode, roleCode)
                .last("limit 1")
        );
        return one;
    }

    @Override
    public ShopUserRoleConfigEntity getByShopIdAndLevel(Long shopId, Integer level) {

        ShopUserRoleConfigEntity one = this.getOne(new LambdaQueryWrapper<ShopUserRoleConfigEntity>()
                .eq(ShopUserRoleConfigEntity::getShopId, shopId)
                .eq(ShopUserRoleConfigEntity::getLevel, level)
                .last("limit 1")
        );
        return one;
    }

    @Override
    public ShopUserRoleConfigEntity update(Long shopId, ShopUserRoleConfigDTO dto) {
        ShopUserRoleConfigEntity load = this.getByShopIdAndId(shopId, dto.getId());
        if (load == null) {
            throw new RRException("商家会员等级配置不存在");
        }
        load.setOuterRoleName(dto.getOuterRoleName());
        load.setThreshold(dto.getThreshold());
        load.setUpgradeNum(dto.getUpgradeNum());
        load.setDiscount(dto.getDiscount());
        this.baseMapper.updateById(load);
        return load;
    }

    @Override
    public List<ShopUserRoleConfigEntity> getByShopId(Long shopId) {
        List<ShopUserRoleConfigEntity> list = this.list(
                new LambdaQueryWrapper<ShopUserRoleConfigEntity>()
                        .eq(ShopUserRoleConfigEntity::getShopId, shopId)
        );

        return list;
    }

    /**
     * 查询该会员的消费额在哪个等级
     *
     * @param shopId
     * @param totalConsumption
     * @return
     */
    @Override
    public ShopUserRoleConfigEntity getByThresholdCompare(Long shopId, BigDecimal totalConsumption) {

        ShopUserRoleConfigEntity one = this.getOne(
                new LambdaQueryWrapper<ShopUserRoleConfigEntity>()
                        .eq(ShopUserRoleConfigEntity::getShopId, shopId)
                        .le(ShopUserRoleConfigEntity::getThreshold, totalConsumption)
                        .ne(ShopUserRoleConfigEntity::getLevel, MemberConstant.MemberLevel.CITY_AGENT)//不算市代
                        .orderByDesc(ShopUserRoleConfigEntity::getThreshold)
                        .last("limit 1")
        );
        return one;
    }

    @Override
    public ShopUserRoleConfigEntity getByNumCompare(Long shopId, Long num) {
        ShopUserRoleConfigEntity one = this.getOne(
                new LambdaQueryWrapper<ShopUserRoleConfigEntity>()
                        .eq(ShopUserRoleConfigEntity::getShopId, shopId)
                        .le(ShopUserRoleConfigEntity::getUpgradeNum, num)
                        .ne(ShopUserRoleConfigEntity::getLevel, MemberConstant.MemberLevel.CITY_AGENT)//不算市代
                        .orderByDesc(ShopUserRoleConfigEntity::getUpgradeNum)
                        .last("limit 1")
        );
        return one;
    }

    @Override
    public ShopUserRoleConfigEntity getLowestLevel(Long shopId) {
        ShopUserRoleConfigEntity one = this.getOne(
                new LambdaQueryWrapper<ShopUserRoleConfigEntity>()
                        .eq(ShopUserRoleConfigEntity::getShopId, shopId)
                        .eq(ShopUserRoleConfigEntity::getLevel, MemberConstant.MemberLevel.GENERAL.getCode())
                        .last("limit 1")
        );
        return one;
    }

    @Override
    public String getRoleNameByRoleCode(Long shopId, String roleCode) {
        ShopUserRoleConfigEntity one = this.getOne(
                new LambdaQueryWrapper<ShopUserRoleConfigEntity>()
                        .eq(ShopUserRoleConfigEntity::getShopId, shopId)
                        .eq(ShopUserRoleConfigEntity::getRoleCode, roleCode)
                        .last("limit 1")
        );
        if (one == null) {
            return MemberConstant.MemberLevel.GENERAL.getValue();//普通会员
        }
        return one.getOuterRoleName();
    }

}
